package com.bing.shiro;

import com.bing.common.config.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {

    /**
     * shiro异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = AuthorizationException.class)
    public Result<?> handleException(AuthorizationException e) {
        String message = e.getMessage();
        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        //判断是角色错误还是权限错误
        if (message.contains("role")) {
            return  Result.error(401,"对不起，您没有" + msg + "角色");
        }else if (message.contains("permission")) {
            return  Result.error(401,"对不起，您没有" + msg + "权限");
        } else {
            return Result.error(401,"对不起，您的权限有误");
        }

    }

    /**
     * 运行异常捕获
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ExceptionHandler(value = RuntimeException.class)
    public Result<?> handler(RuntimeException e){
        log.error("运行异常----------");
        return Result.error(502,"运行异常!");
    }
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------", e);
        return Result.error(502,e.getMessage());
    }

    /**
     * 实体校验异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handler(MethodArgumentNotValidException e){
        log.error("实体校验异常----------");
        BindingResult bindingResult = e.getBindingResult();
        ObjectError error = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.error(502,error.getDefaultMessage());
    }

    @ResponseStatus(value = HttpStatus.BAD_GATEWAY)
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result<?> handler(MaxUploadSizeExceededException e){
        log.error("文件超出异常----------",e.getMessage());
        return Result.error(502,"文件上传过大");
    }

}

